import express from 'express';
import { authenticateToken } from '../middleware/auth.js';
import User from '../models/user.js';
import pool from '../config/db.js';

const router = express.Router();

// 获取购物车
router.get('/', authenticateToken, async (req, res) => {
  try {
    console.log('Getting cart for user:', req.user.id);
    const cart = await User.getCart(req.user.id);
    console.log('Raw cart data:', cart);
    
    // 处理图片路径
    const processedCart = cart.map(item => ({
      ...item,
      image: item.image && !item.image.startsWith('http')
        ? `${req.protocol}://${req.get('host')}/uploads/${item.image}`
        : item.image
    }));
    
    console.log('Processed cart data:', processedCart);
    
    res.json({
      success: true,
      items: processedCart
    });
  } catch (error) {
    console.error('Error in GET /cart:', error);
    res.status(500).json({ 
      success: false,
      message: '获取购物车失败',
      error: process.env.NODE_ENV === 'production' ? {} : error.message
    });
  }
});

// 添加商品到购物车
router.post('/', authenticateToken, async (req, res) => {
  try {
    const { product_id, quantity, attributes } = req.body;
    
    if (!product_id) {
      return res.status(400).json({ 
        success: false,
        message: '商品ID不能为空' 
      });
    }
    
    const cartItemId = await User.addToCart(
      req.user.id, 
      product_id, 
      quantity || 1,
      attributes
    );
    
    res.status(201).json({ 
      success: true,
      message: '商品已添加到购物车',
      cart_item_id: cartItemId
    });
  } catch (error) {
    console.error('Error in POST /cart:', error);
    res.status(500).json({ 
      success: false,
      message: '添加到购物车失败',
      error: process.env.NODE_ENV === 'production' ? {} : error.message
    });
  }
});

// 更新购物车商品数量
router.put('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const { quantity } = req.body;
    
    // 验证数量
    const parsedQuantity = parseInt(quantity);
    if (!parsedQuantity || parsedQuantity < 1) {
      return res.status(400).json({
        success: false,
        message: '数量必须大于0'
      });
    }

    // 使用 User model 的方法更新数量
    const result = await User.updateCartItemQuantity(req.user.id, id, parsedQuantity);
    
    res.json({
      success: true,
      message: '数量已更新',
      data: result
    });
  } catch (error) {
    console.error('Error updating cart item:', error);
    res.status(500).json({
      success: false,
      message: error.message || '更新失败'
    });
  }
});

// 删除购物车商品
router.delete('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    
    console.log(`Deleting cart item ${id} for user ${req.user.id}`);
    
    await User.removeFromCart(req.user.id, id);
    
    res.json({
      success: true,
      message: '商品已从购物车中移除'
    });
  } catch (error) {
    console.error('Error in DELETE /cart/:id:', error);
    res.status(500).json({
      success: false,
      message: error.message || '从购物车中移除商品失败'
    });
  }
});

// 清空购物车
router.delete('/', authenticateToken, async (req, res) => {
  try {
    await User.clearCart(req.user.id);
    
    res.json({
      success: true,
      message: '购物车已清空'
    });
  } catch (error) {
    console.error('Error in DELETE /cart:', error);
    res.status(500).json({
      success: false,
      message: '清空购物车失败'
    });
  }
});

// 应用优惠码
router.post('/promo', authenticateToken, async (req, res) => {
  try {
    const { code } = req.body;
    
    if (!code) {
      return res.status(400).json({ 
        success: false,
        message: '优惠码不能为空' 
      });
    }
    
    // 获取购物车总金额
    const [cartItems] = await pool.query(`
      SELECT p.price, ci.quantity 
      FROM cart_items ci 
      JOIN carts c ON ci.cart_id = c.id 
      JOIN products p ON ci.product_id = p.id 
      WHERE c.user_id = ?`,
      [req.user.id]
    );
    
    const subtotal = cartItems.reduce((sum, item) => sum + (item.price * item.quantity), 0);
    
    // 验证优惠码
    const [promos] = await pool.query(
      `SELECT * FROM promo_codes 
       WHERE code = ? 
       AND status = 'active' 
       AND (expires_at IS NULL OR expires_at > NOW())`,
      [code]
    );
    
    if (promos.length === 0) {
      return res.status(400).json({
        success: false,
        message: '无效的优惠码'
      });
    }
    
    const promo = promos[0];
    
    // 检查最低消费要求
    if (promo.min_purchase && subtotal < promo.min_purchase) {
      return res.status(400).json({
        success: false,
        message: `订单金额需满${promo.min_purchase}元才能使用此优惠码`
      });
    }
    
    // 计算折扣金额
    let discountAmount = 0;
    if (promo.discount_type === 'percentage') {
      discountAmount = subtotal * (promo.discount_value / 100);
    } else {
      discountAmount = promo.discount_value;
    }
    
    // 确保折扣不超过订单金额
    discountAmount = Math.min(discountAmount, subtotal);
    
    res.json({ 
      success: true,
      message: '优惠码已应用',
      discount: {
        code: promo.code,
        discountAmount: discountAmount,
        type: promo.discount_type,
        value: promo.discount_value
      }
    });
  } catch (error) {
    console.error('Error in POST /cart/promo:', error);
    res.status(500).json({ 
      success: false,
      message: error.message || '应用优惠码失败'
    });
  }
});

// 计算配送费
router.post('/shipping', authenticateToken, async (req, res) => {
  try {
    const { country, province, city, postcode } = req.body;
    
    if (!country) {
      return res.status(400).json({ 
        success: false,
        message: '国家/地区不能为空' 
      });
    }
    
    const result = await User.calculateShipping(req.user.id, {
      country,
      province,
      city,
      postcode
    });
    
    res.json({ 
      success: true,
      ...result
    });
  } catch (error) {
    console.error('Error in POST /cart/shipping:', error);
    res.status(500).json({ 
      success: false,
      message: error.message || '计算配送费失败'
    });
  }
});

// 获取用户的地址
router.get('/addresses', authenticateToken, async (req, res) => {
  try {
    const [addresses] = await pool.query(`
      SELECT 
        id,
        name,
        phone,
        province,
        city,
        address,
        postcode,
        created_at,
        updated_at
      FROM addresses 
      WHERE user_id = ? 
      ORDER BY created_at DESC`,
      [req.user.id]
    );
    
    res.json(addresses);
  } catch (error) {
    console.error('Error fetching addresses:', error);
    res.status(500).json({ 
      success: false, 
      message: '获取地址失败' 
    });
  }
});

// 调试路由 - 仅用于开发环境
router.get('/debug', authenticateToken, async (req, res) => {
  try {
    // 测试数据库连接
    const connection = await pool.getConnection();
    
    // 测试购物车表查询
    const [cartItems] = await connection.query(
      'SELECT * FROM cart_items WHERE user_id = ?',
      [req.user.id]
    );
    
    // 测试产品表查询
    const [products] = await connection.query(
      'SELECT * FROM products LIMIT 5'
    );
    
    connection.release();
    
    res.json({
      success: true,
      message: '调试信息',
      user_id: req.user.id,
      cart_items: cartItems,
      sample_products: products
    });
  } catch (error) {
    console.error('Debug route error:', error);
    res.status(500).json({
      success: false,
      message: '调试失败',
      error: error.message
    });
  }
});

// 清除已支付订单的购物车商品
router.post('/clear-paid', authenticateToken, async (req, res) => {
  try {
    const { order_no } = req.body;
    
    if (!order_no) {
      return res.status(400).json({
        success: false,
        message: '订单号不能为空'
      });
    }
    
    // 查询订单信息
    const [orders] = await pool.query(
      'SELECT * FROM orders WHERE order_no = ? AND user_id = ?',
      [order_no, req.user.id]
    );
    
    if (orders.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    const order = orders[0];
    
    // 查询订单商品
    const [orderItems] = await pool.query(
      'SELECT * FROM order_items WHERE order_id = ?',
      [order.id]
    );
    
    // 从购物车中删除这些商品
    for (const item of orderItems) {
      if (!item.attributes || Object.keys(item.attributes).length === 0) {
        // 如果没有属性，直接按产品ID删除
        await pool.query(
          'DELETE FROM cart_items WHERE user_id = ? AND product_id = ? AND (attributes IS NULL OR JSON_LENGTH(attributes) = 0)',
          [req.user.id, item.product_id]
        );
      } else {
        // 如果有属性，使用JSON_CONTAINS匹配
        await pool.query(
          'DELETE FROM cart_items WHERE user_id = ? AND product_id = ? AND JSON_CONTAINS(attributes, ?)',
          [req.user.id, item.product_id, JSON.stringify(item.attributes)]
        );
      }
    }
    
    // 更新订单状态为已支付
    await pool.query(
      'UPDATE orders SET status = ?, payment_status = ?, updated_at = NOW() WHERE id = ?',
      ['paid', 'paid', order.id]
    );
    
    // 更新支付状态
    await pool.query(
      'UPDATE payments SET status = ?, updated_at = NOW() WHERE order_id = ? AND status = ?',
      ['paid', order.id, 'pending']
    );
    
    res.json({
      success: true,
      message: '购物车已更新'
    });
  } catch (error) {
    console.error('Error clearing cart after payment:', error);
    res.status(500).json({
      success: false,
      message: '清除购物车失败'
    });
  }
});

export default router; 